import {
  Injectable,
  CanActivate,
  ExecutionContext,
  UnauthorizedException,
  ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { IsArray } from 'lodash';

// 定义逻辑类型
type PermissionLogic = 'AND' | 'OR';

@Injectable()
export class PermissionGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const permissionsInfo = this.reflector.get<{
      // permissions: string[] | string;
      permissions: any;
      logic: PermissionLogic;
    }>('requiredPermission', context.getHandler());

    if (!permissionsInfo) {
      return true;
    }

    let { permissions, logic } = permissionsInfo;
    logic = logic || 'AND';
    permissions = Array.isArray(permissions) ? permissions : [permissions];
    const request = context.switchToHttp().getRequest<Request>();
    const user = request['user'];

    if (!user || !user.permissions) {
      throw new ForbiddenException();
    }

    if (logic === 'AND') {
      return permissions.every((permission) =>
        user.permissions.includes(permission),
      );
    } else {
      return permissions.some((permission) =>
        user.permissions.includes(permission),
      );
    }
  }
}
